﻿using DotNetty.Codecs.Http;
using DotNetty.Common.Utilities;
using DotNetty.Framework;
using DotNetty.Framework.BaseModel;
using System.IO;
using System.Threading.Tasks;

namespace iTool.Connector.HttpWorkers
{
    public class ImageViewWorker : IHttpWorker
    {

        public int SecondOfTimeOut { get; set; } = 10;

        public async Task DoWorking<THttpContext>(THttpContext context) where THttpContext : AbstractHttpContext, new()
        {

            await using (FileStream fs = new FileStream("./face.png", FileMode.Open, FileAccess.Read))
            {
                BinaryReader r = new BinaryReader(fs);
                context.ResponseBody = r.ReadBytes((int)fs.Length);

                // set type
                context.ResponseHeader.Add(new AsciiString("Content-Type"), FileContentType.GetMimeType(fs.Name));
                // cache
                context.ResponseHeader.Add(new AsciiString("Pragma"), "public");
                context.ResponseHeader.Add(new AsciiString("Cache-Control"), "public");
                // set filename
                context.ResponseHeader.Add(new AsciiString("Content-Disposition"), $"filename=\"{fs.Name}\"");
            }

            context.ResponseStatus = HttpResponseStatus.OK;

        }

        public bool IsUseWorking<THttpContext>(THttpContext context) where THttpContext : AbstractHttpContext, new()
        {
            return context.Path.ToLower() == "/viewimg";
        }

    }
}
